from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from ..models import UserProfile, Book

# Django REST framework 序列化
# 1. 用 serializers.Serializer 方式序列化
# 2. 用 serrializers.ModelSerializer 方式序列化（推荐）


class BookSerializer(serializers.Serializer):
    title = serializers.CharField(required=True, max_length=100)
    isbn = serializers.CharField(required=True, max_length=100)
    author = serializers.CharField(required=True, max_length=100)
    publish = serializers.CharField(required=True, max_length=100)
    rate = serializers.FloatField(default=0)


class BookAPIView1(APIView):
    """
    使用Serializer序列化（需要声明字段，影响开发效率，不常用，了解即可）
    """

    def get(self, request, format = None):
        # UserProfile.objects.create(APIkey='auser', money=10)
        # Book.objects.create(title='一个书名', isbn='777777', author='一个作者', publish='一个出版社', rate=6.6)
        # return Response("ok")
        apikey = self.request.query_params.get('apikey', 0)
        developer = UserProfile.objects.filter(APIkey=apikey).first()
        if developer:
            balance = developer.money
            if balance > 0:
                isbn = self.request.query_params.get('isbn', 0)
                books = Book.objects.filter(isbn=int(isbn))
                books_serializer = BookSerializer(books, many=True)
                developer.money -= 1
                developer.save()
                return Response(books_serializer.data)
            else:
                return Response("兄弟，没钱了！")
        else:
            return Response("查无此人")


class BookModelSerializer(serializers.ModelSerializer):
    class Meta:
        model=Book
        # fields=('title', 'isbn', 'author') # 指定序列化某些字段
        fields="__all__" # 将整个表的所有字段都序列化


class BookAPIView2(APIView):
    """
    使用ModelSerializer序列化（与BookSerializer相比，只是序列化的方式不同，其他都是一样的，实际开发中通常使用该方式）
    """

    def get(self, request, format = None):
        # User.objects.filter(APIkey="auser").update(money=10)
        # return Response("ok")
        apikey = self.request.query_params.get('apikey', 0)
        developer = UserProfile.objects.filter(APIkey=apikey).first()
        if developer:
            balance = developer.money
            if balance > 0:
                isbn = self.request.query_params.get('isbn', 0)
                books = Book.objects.filter(isbn=int(isbn))
                books_serializer = BookModelSerializer(books, many=True)
                developer.money -= 1
                developer.save()
                return Response(books_serializer.data)
            else:
                return Response("兄弟，没钱了！")
        else:
            return Response("查无此人")

